package com.example.demo.create.prototype;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @Desc:
 * @Author zzz
 * @Date 2021/2/20
 * @Version V1.0
 */
@Data
@NoArgsConstructor
public class Monkey implements Cloneable, Serializable {

    private static final long serialVersionUID = 7653776189360470545L;

    private String name;
    private Monkey son;

    public Monkey(String name) {
        this.name = name;
    }

    public Monkey clone() throws CloneNotSupportedException {
        return (Monkey) super.clone();
    }

    public static Object deepCopy(Object from) {
        Object obj = null;
        try {
            // 将对象写成 Byte Array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(from);
            out.flush();
            out.close();
            // 从流中读出 byte array，调用readObject函数反序列化出对象
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            obj = in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e2) {
            e2.printStackTrace();
        }
        return obj;
    }


    public static void main(String[] args) throws CloneNotSupportedException {
        Monkey monkeySon = new Monkey("MonkeySon");
        Monkey monkey = new Monkey("SunWuKong");
        monkey.setSon(monkeySon);

        Monkey monkey1 = monkey.clone();
        Monkey monkey2 = (Monkey) deepCopy(monkey);

        System.out.println(monkey.getName() + "---------" + monkey.getSon().getName());
        System.out.println(monkey1.getName() + "---------" + monkey1.getSon().getName());
        System.out.println(monkey2.getName() + "---------" + monkey2.getSon().getName());

        System.out.println(monkey.equals(monkey1));
        System.out.println(monkey.equals(monkey2));

        monkey.setName("SunWuFan");
        monkey.getSon().setName("hahaha");
        System.out.println(monkey.getName() + "---------" + monkey.getSon().getName());
        System.out.println(monkey1.getName() + "---------" + monkey1.getSon().getName());
        System.out.println(monkey2.getName() + "---------" + monkey2.getSon().getName());

        System.out.println(monkey.equals(monkey1));
        System.out.println(monkey.equals(monkey2));
    }

}
